<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <title>Java后端WebSocket的Tomcat测试</title>
        <script type="text/javascript" src="res_js/jquery-3.7.0.min.js"></script>
        <script type="text/javascript" src="res_js/message-plus.js"></script>
        <script type="text/javascript" src="res_js/axios-0.18.0.js"></script>
    </head>
    <body style="width: 455px; height: 325px; border: 1px black solid; margin: 0">
        <div style="width: 455px">
            输入ID：<input id="my_id" type="text" value="" style="width: 162px; height: 15px"><br>
            端口：<input id="port" type="text" value="8081">
            <button id="joinBtn" onclick="join()">立即连接</button>
            <button onclick="closeWebSocket()">关闭WebSocket连接</button>
        </div>
        <hr>
        <div>
            发送方：<input id="friendId" type="text" style="width: 162px; height: 15px">
            <br>
            发送次数：<input id="sendFrequency" type="number" name="quantity" min="1" max="100" value="1">
            发送频率：<input id="sendTime" type="number" name="quantity" min="1" max="1000" value="1">ms
        </div>
        <div>
            是否清空内容：<input id="clearContent" type="checkbox" checked>
            内容：<input id="msgContent" type="text" style="width: 162px; height: 15px">
            <button id="sendMessage" onclick="send()">发送消息</button>
        </div>
        <hr style="margin-bottom: 0">
        <div id="message" style="height: 190px; overflow: auto"></div>
    </body>
    <script>
        const wsUrl = "ws://localhost:8081/messageplus/ws/";
        function getWsUrl(port) {
            return "ws://localhost:"+port+"/messageplus/ws/"
        }
        // 我的ID
        var MY_ID = undefined;
        // 服务器端口
        var PORT = undefined;
        // 套接字
        var websocket = null;
        // 连接服务器
        function join() {
            MY_ID = document.getElementById('my_id').value;
            if (MY_ID===undefined) return;
            PORT = document.getElementById('port').value;
            document.getElementById('joinBtn').disabled = true;
            document.getElementById('message').innerHTML = '';
            //判断当前浏览器是否支持WebSocket
            if('WebSocket' in window) {
                //改成你的地址
                websocket = new WebSocket(getWsUrl(PORT)+MY_ID);
            } else {
                alert('当前浏览器 Not support websocket')
            }

            //连接发生错误的回调方法
            websocket.onerror = function() {
                setMessageInnerHTML("WebSocket连接发生错误");
            };

            //连接成功建立的回调方法
            websocket.onopen = function() {
                setMessageInnerHTML("WebSocket连接成功");
            }

            //接收到消息的回调方法
            websocket.onmessage = function(event) {
                // console.log(event);
                setMessageInnerHTML(event.data);
            }

            //连接关闭的回调方法
            websocket.onclose = function() {
                setMessageInnerHTML("WebSocket连接关闭");
            }

            //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            window.onbeforeunload = function() {
                closeWebSocket();
            }
        }

        //将消息显示在网页上
        function setMessageInnerHTML(innerHTML) {
            document.getElementById('message').innerHTML += innerHTML + '<br/>';
        }

        //关闭WebSocket连接
        function closeWebSocket() {
            websocket.close();
            document.getElementById('joinBtn').disabled = false;
        }

        //发送消息
        function send() {
            document.getElementById('sendMessage').disabled = true;
            // 获取消息内容
            var msgContent = document.getElementById('msgContent').value;
            if (msgContent==='') return;
            // 是否清空输入框
            var isClearContent = document.getElementById('clearContent').checked;
            if (isClearContent) document.getElementById('msgContent').value = '';

            var message = {};
            message.friendId = document.getElementById('friendId').value;
            message.msg = msgContent;
            // websocket.send('{"msg":"' + msgContent + '"}');
            // 获取发送次数
            var sendFrequency = document.getElementById('sendFrequency').value;
            // 获取发送频率
            var sendTime = document.getElementById('sendTime').value;
            // 循环发送
            let i = 0;
            sm();
            function sm() {
                setTimeout(()=>{
                    axios({
                        method: "post",
                        url: window.location.protocol + "//" + window.location.host + "/messageplus/send/single",
                        headers: {
                            'Content-Type': 'application/json;charset=UTF-8'
                        },
                        params: {
                            id1: MY_ID,
                            id2: message.friendId,
                        },
                        data: msgContent
                    }).then(resp => {}).catch(err => {});
                    i++;
                    if (i<sendFrequency) sm();
                    else {
                        document.getElementById('sendMessage').disabled = false;
                    }
                },sendTime);
            }
            // for (let i = 0; i < sendFrequency; i++) {
                // websocket.send(JSON.stringify(NewSingleShotMessage(message.friendId, message)));
                // setMessageInnerHTML(msgContent + "&#13;");
            // }
        }
    </script>
</html>